package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Sms;
import cn.wolfcode.trip.base.service.ISmsService;
import cn.wolfcode.trip.base.util.JasonResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RequestMapping("/sms")
@RestController
public class SmsController {

    @Autowired
    private ISmsService service ;


    /**
     * 删除一条私信
     * 资源：/sms/{id}
     * 动作：DELETE
     * 参数：
     *
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id, HttpServletResponse resp){
        service.delete(id);
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }


    /**
     * 错误的设计
     * 拿到指定用户的所有私信信息
     * 参数：
     * 资源：/sms/{id}
     * 动作：Get
     */
    @GetMapping("/{id}")
    public Object getSmsByUserId(@PathVariable Long id){
        return service.getSmsByUserId(id);
    }


    /**
     * 新增一条私信
     * 参数：一个私信对象
     *资源：/sms
     * 动作：POST
     */
    @PostMapping
    public Object save(Sms sms, MultipartFile pic){
        JasonResult jr = new JasonResult();
        //判断用户有没有上传正确的图片文件
        if(pic!=null&&pic.getContentType().startsWith("image")&&pic.getSize()>0){
            //把上传的图片保存到本地的图库中去
            String path = UploadUtil.upload(pic);
            sms.setImg(path);
        }
        try {
            service.save(sms);
        } catch (Exception e) {
            e.printStackTrace();
            jr.mark(e.getMessage());
        }
        return jr ;
    }
}
